package net.controller;

import net.mapper.UserMapper;
import net.pojo.Artile;
import net.pojo.Comments;
import net.pojo.User;
import net.service.ArtileService;
import net.service.CommentsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

/**
 * @Author admin
 * @Date 2019/5/28 8:41
 */
@Controller
@RequestMapping("/comments")
public class CommentsController {
    @Autowired
    CommentsService commentsService;
    @Autowired
    ArtileService artileService;
    @Autowired
    UserMapper userMapper;

    @RequestMapping("/findPageByUid")
    public String findPageByUid(HttpSession session,Model model){
        User user = (User) session.getAttribute("user");
        if ( user == null){
            session.setAttribute("result",3);
            List<Comments> commentsList = commentsService.findAll();
            //根据点击量排行
            List<Artile> clickList = artileService.findByClick();
            //最新评论
            List<Comments> commentssList = commentsService.findByCtime();
            model.addAttribute("commentsList", commentsList);
            model.addAttribute("clickList", clickList);
            model.addAttribute("commentssList", commentssList);
            return "/client/about.jsp";
        }else {
            List<Comments> commentsList = commentsService.findPageByUid(user.getUid());
            List<Artile> clickList = artileService.findByClick();
            //最新评论
            List<Comments> commentssList = commentsService.findByCtime();
            model.addAttribute("commentsList",commentsList);
            model.addAttribute("clickList",clickList);
            model.addAttribute("commentssList",commentssList);
            return "/client/about.jsp";
        }
    }

    @RequestMapping("/addComment")
    @ResponseBody
    public List<Comments> addComment(Comments comments,HttpSession session){
        User user = (User) session.getAttribute("user");
        comments.setUsid(user.getUid());
        comments.setCtime(new Date());
        comments.setUser(user);
        commentsService.addComments(comments);
        List<Comments> list = commentsService.findAll();
        for (Comments comments1 : list){
            User user1 = userMapper.findById(comments.getUsid());
            comments1.setUser(user1);
        }
        return list;
    }

}
